package com.mrs.gauss.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mrs.gauss.common.ErrorCode;
import com.mrs.gauss.exception.BusinessException;
import com.mrs.gauss.interfaces.basicAuth.BasicAuthAccess;
import com.mrs.gauss.interfaces.basicAuth.HttpManager;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.HttpClient;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * HttpClient自带的HttpDelete方法是不支持上传body的，所以重写delete方法
 * 采集告警列表
 *
 */
@Log4j2
public class MrsClusterServerAlarms {
    /* 查询按时间倒叙，状态是未恢复的告警
     告警类型。取值范围：0：全部（默认）1 : 未恢复告警 2 : 已恢复告警
     告警级别。0：全部（默认）1 : Critical 2 : Major 3 : Minor 4 : Warning*/
    private static final String QUERY_ALARMS_LIST_URL = "/api/v3/alarms?limit=1000&offset=0&status=1&order=desc"
            + "&order_by=occurTime";


    /**
     * 程序运行入口
     *
     */
    public  List<Map> getServerAlarmsList() {
        // 文件UserInfo.properties的路径
        String userFilePath = "./conf/UserInfo.properties";
        InputStream userInfo = null;
        ResourceBundle resourceBundle = null;
        List<Map> result = new ArrayList<>();
        // 初始化17天的状态Map，key为日期，value为状态(0/1)
        Map<String, Integer> statusMap = new LinkedHashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        statusMap.put("currentSatus", 0);//当日实时值
        // 初始化17天的数据，默认状态为0
        for (int i = 0; i < 17; i++) {
            String date = sdf.format(calendar.getTime());
            statusMap.put(date, 0);
            calendar.add(Calendar.DATE, -1);
        }

        try {
            File file = new File(userFilePath);
            if (!file.exists()) {
                log.error("The user info file doesn't exist.");
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "集群用户属性文件不存在");
            }
//            log.info("Get the web info and user info from file {} ", file);

            userInfo = new BufferedInputStream(new FileInputStream(file));
            resourceBundle = new PropertyResourceBundle(userInfo);

            // 获取用户名
            String userName = resourceBundle.getString("userName");
//            log.info("The user name is : {}.", userName);
            if (userName == null || userName.isEmpty()) {
                log.error("The userName is empty.");
            }

            // 获取用户密码
            String password = resourceBundle.getString("password");
            if (password == null || password.isEmpty()) {
                log.error("The password is empty.");
            }

            String webUrl = resourceBundle.getString("webUrl");
//            log.info("The webUrl is : {}.", webUrl);


            // userTLSVersion是必备的参数，是处理jdk1.6服务端连接jdk1.8服务端时的重要参数，如果用户使用的是jdk1.8该参数赋值为空字符串即可
            String userTLSVersion = "";

            // 调用firstAccess接口完成登录认证
//            log.info("Begin to get httpclient and first access.");
            BasicAuthAccess authAccess = new BasicAuthAccess();
            HttpClient httpClient = authAccess.loginAndAccess(webUrl, userName, password, userTLSVersion);

//            log.info("Start to access REST API.");

            HttpManager httpManager = new HttpManager();
            String operationName = "";
            String operationUrl = "";

            // 访问大数据集群接口完成查找alarms列表
            operationName = "getServerAlarmsList";
            operationUrl = webUrl + QUERY_ALARMS_LIST_URL;
            String responseLineContent = httpManager.sendHttpGetRequest(httpClient, operationUrl, operationName);
           /* log.info("未恢复的告警列表：");
            log.info("The {} response is {}.", operationName, alarmsList);*/

//          服务不可用监控：监控：ALM-13000(zookeeper)、ALM-14000(HDFS)、ALM-18000(yarn)、ALM-16004(hive)、ALM-19000(hbase)、ALM-43200 (ES)、ALM-38000（kafka）
            String searchZKId = "ALM-13000";
            String searchHdfsId = "ALM-14000";
            String searchYarnId = "ALM-18000";
            String searchHiveId = "ALM-16004";
            String searchHbaseId = "ALM-19000";
            String searchESId = "ALM-43200";
            String searchKafkaId = "ALM-38000";

            if (!responseLineContent.contains(searchZKId) && !responseLineContent.contains(searchHdfsId) && !responseLineContent.contains(searchYarnId)
                    && !responseLineContent.contains(searchHiveId)
            && !responseLineContent.contains(searchHbaseId) && !responseLineContent.contains(searchESId) && !responseLineContent.contains(searchKafkaId)) {
                // 无告警时不需要任何操作
            } else {
                log.warn("存在服务不可用告警");
                // 获取当前日期并更新状态为1
                String today = sdf.format(new Date());
                statusMap.put(today, 1);
                statusMap.put("currentSatus", 1); //当日实时值
            }
            // 在添加total之前计算总和
            int total = statusMap.entrySet().stream()
                    .filter(entry -> !entry.getKey().equals("currentSatus") && !entry.getKey().equals("total"))
                    .mapToInt(Map.Entry::getValue)
                    .sum();
            statusMap.put("total", total);
        } catch (IOException e) {
            log.error(e.getMessage());
        } catch (Throwable e) {
            log.error(e.getMessage());
        } finally {
            if (userInfo != null) {
                try {
                    userInfo.close();
                } catch (IOException e) {
                    log.error("IOException.");
                }
            }
        }
        result.add(statusMap);
        return result;
    }
}
